package org.smartjava.concurrent.juc;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * ForkJoinTask
 * {@link java.util.concurrent.ForkJoinTask}
 * {@link java.util.concurrent.CountedCompleter}
 * {@link java.util.concurrent.RecursiveAction}
 * {@link java.util.concurrent.RecursiveTask}
 */
public class ForkJoinExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1();
        test2();
        test3();
    }

    public static void test1() {
        Long sum = 0L;
        long start = System.currentTimeMillis();
        for (Long i = 1L; i <= 1_0000_0000L; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("Normal sum=" + sum + " 时间：" + (end - start));
    }

    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        MyForkJoin myForkJoin = new MyForkJoin(1L, 1_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(myForkJoin);
        Long sum = submit.get();
        long end = System.currentTimeMillis();
        System.out.println("MyForkJoin sum=" + sum + " 时间：" + (end - start));
    }

    public static void test3() {
        long start = System.currentTimeMillis();
        // Stream并行流 ()  (]
        long sum = LongStream.rangeClosed(0L, 1_0000_0000L).parallel().reduce(0, Long::sum);
        long end = System.currentTimeMillis();
        System.out.println("LongStream sum=" + sum + " 时间：" + (end - start));
    }


}

class MyForkJoin extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    private static Long temp = 1_000L;

    MyForkJoin(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if (end - start <= temp) {
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            Long middle = (end + start) / 2;
            MyForkJoin myForkJoin1 = new MyForkJoin(start, middle);
            myForkJoin1.fork();
            MyForkJoin myForkJoin2 = new MyForkJoin(middle + 1, end);
            myForkJoin2.fork();
            return myForkJoin1.join() + myForkJoin2.join();
        }

    }
}
